import http from "@/http";
import { acceptHMRUpdate, defineStore } from "pinia";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { layer } from "@layui/layer-vue";
// 第一个参数是应用程序中 store 的唯一 id
export const useCounterStore = defineStore("counter", () => {
  const token = ref<string>("");
  const deviceId = ref<string>("test");
  const system = ref<any>([]);
  const router = useRouter();
  // 当前菜单的按钮权限
  const nowMenuBtn = ref<any>([]);
  const nowMenuBtnArr = ref<string[]>([]);
  const nowMenuBtnArrKeys = ref<string[]>([]);
  // tab menu、
  const tabMenu = ref<any>([]);
  // menu菜单
  // 当前选中
  const selectedKey = ref<string>("user");
  // 打开项
  const openKeys6 = ref<string[]>(["0"]);

  // 控制菜单折叠
  const collapse = ref<boolean>(true);
  // 面包屑导航
  const menuTab = ref([
    {
      title: "首页",
      key: "home",
    },
  ]);
  const menuList = ref([]);
  const newMmenuList = ref<any>([]);
  const allMenuList = ref([]);
  // 菜单数据

  const get_menu_list = async () => {
    const res = await http.corsApi(
      "/secPermission/treeSelectByResKey",
      "get",
      {}
    );
    // console.log(res);

    menuList.value = res.data[0].children;

    menuList.value.map((item: any) => {
      if (item.children) {
        item.children.map((ele: any) => {
          ele["hasChildren"] = true;
        });
      }
    });
    console.log(menuList.value);
  };

  // 获取当前人路由数据
  const get_router = async () => {
    // console.log(window.location);

    // if (window.location.href.split("#")[1] == "/login") {
    //   return false;
    // }

    const res = await http.corsApi(
      "/secPermission/generatorRouters",
      "get",
      {}
    );
    console.log(res);
    allMenuList.value = res.data;
    let data = res.data;
    let parentData: any = [];
    // 父级菜单
    data.forEach((ele: any) => {
      if (ele.permissionType == 0 && ele.permissionIshide == 1) {
        parentData.push(ele);
      }
    });

    // 父级菜单放子集菜单
    parentData.forEach((item: any) => {
      item["children"] = [];
      for (const ele of data) {
        // console.log(ele);
        if (
          item.permissionId == ele.permissionParentId &&
          ele.permissionIshide == 1
        ) {
          item["children"].push(ele);
        }
      }
    });

    // parentData.unshift({
    //   permissionComponet: "Layout",
    //   permissionIcon: "",
    //   permissionId: "home",
    //   permissionIshide: "1",
    //   permissionKey: "",
    //   permissionLevel: 1,
    //   permissionName: "首页",
    //   permissionParentId: "TOP",
    //   permissionType: "0",
    //   permissionUrl: "/home",
    // });
    // console.log(parentData);
    newMmenuList.value = parentData;
    // console.log(newMmenuList.value[0].permissionUrl);

    if (newMmenuList.value[0] && newMmenuList.value[0].children.length > 0) {
      router.push(newMmenuList.value[0].children[0].permissionUrl);
      openKeys6.value = newMmenuList.value[0].permissionId;
      selectedKey.value = newMmenuList.value[0].children[0].permissionId;
      get_now_router(newMmenuList.value[0].children[0].permissionId);
    }
  };

  // 获取当前页面的按钮权限
  const get_now_router = async (id: number | string) => {
    // console.log(id);
    // console.log(allMenuList.value);
    if (!allMenuList.value.length || allMenuList.value.length <= 0) {
      await get_router();
    }

    // nowMenuBtn.value = [];
    // nowMenuBtnArr.value = [];

    try{
      nowMenuBtnArrKeys.value = [];
      allMenuList.value.forEach((ele: any) => {
        if (ele.permissionParentId == id) {
          // console.log(ele);
          nowMenuBtnArrKeys.value.push(ele.permissionId);
              if (
                ele.permissionName == "新增" ||
                ele.permissionName == "增加" ||
                ele.permissionName == "添加"
              ) {
                nowMenuBtnArr.value.push("新增");
                nowMenuBtnArr.value.push("增加");
                nowMenuBtnArr.value.push("添加");
  
              }
              if (ele.permissionName == "修改" || ele.permissionName == "编辑") {
                nowMenuBtnArr.value.push("修改");
                nowMenuBtnArr.value.push("编辑");
              }
              if (ele.permissionName == "查看" || ele.permissionName == "详情") {
                nowMenuBtnArr.value.push("查看");
                nowMenuBtnArr.value.push("详情");
              }
  
              nowMenuBtn.value.push(ele);
              nowMenuBtnArr.value.push(ele.permissionName.trim());
        }
      });
      nowMenuBtnArr.value = Array.from(new Set(nowMenuBtnArr.value));
      console.log(nowMenuBtnArrKeys.value);
    }catch(err){
      console.log(err)
    }
  };

  const userFromRef = ref();
  const userForm = ref([]);
  const userRules = ref({
    phonenum: {
      validator(rule, value, callback, source, options) {
        console.log(rule, value.length);

        if (Number.isNaN(value * 1)) {
          callback(new Error(`${rule.field}格式不正确`));
        } else if (value.length !== 11) {
          callback(new Error(`${rule.field}长度不正确`));
        } else {
          return true;
        }
      },
    },
  });

  const user_enter = (val) => {
    console.log(val);

    userFromRef.value.validate(async (isValidate, model, errors) => {
      console.log(isValidate);

      console.log(userForm.value);

      // console.log(isShowUserCenterRef.value);

      if (isValidate) {
        const res = await http.corsApi("/secUser/modify", "put", {
          ...userForm.value,
        });
        console.log(res); 
        if (res.data) {
          // system.value.signUrl = res.data.

          isShowUserCenterRef.value.close();

          system.value.signUrl = userForm.value.signBase
          layer.msg("修改成功", { icon: 1, time: 2000 });
        }
      }
    });
  };

  // 获取用户的详情信息
  const get_user_list = async () => {
    const res = await http.corsApi("/secUser/userDetail", "get", {});
    console.log(res);
    userForm.value = res.data
  };

  // 删除个人中心设置
  const isShowUserCenterRef = ref();

  // get_router()
  return {
    token,
    deviceId,
    collapse,
    menuTab,
    get_menu_list,
    menuList,
    get_router,
    newMmenuList,
    nowMenuBtn,
    nowMenuBtnArr,
    get_now_router,
    system,
    selectedKey,
    openKeys6,
    tabMenu,
    allMenuList,
    nowMenuBtnArrKeys,
    isShowUserCenterRef,
    get_user_list,
    userForm,
    userRules,
    userFromRef,
    user_enter,
  };
});

// 开启store热更新
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot));
}
